from time import sleep

from kj_d1.Config.config import UseConfig, useConfig
from kj_d1.base.base import request_action
from kj_d1.base.session import get_app_id

from random import randint

from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException


def get_app_list(uc, app_nm=None):
    if app_nm is None:
        params = {
            'AppType': 'knowledge_qa',
            'PageSize': 10,
            'PageNumber': 1
        }
    else:
        params = {
            'AppType': 'knowledge_qa',
            'Keyword': app_nm,
            'PageSize': 10,
            'PageNumber': 1
        }
    res = request_action(uc, 'ListApp', params=params)
    return res['Response']['List']


def create_app(app_nm=None):
    uc = UseConfig()
    if app_nm is None:
        app_nm = get_app_id()
    app_params = {
        'Name': app_nm,
        'Avatar': 'https://cdn.xiaowei.qq.com/static/lke/app-icon-knowledge_qa.png'
    }

    params = {
        'AppType': 'knowledge_qa',
        'BaseConfig': app_params
    }
    uc.bot_name = app_nm
    sleep(randint(0, 5))
    try:
        res = request_action(uc, 'CreateApp', params=params)
        uc.bot_biz_id = res['Response']['AppBizId']
    except TencentCloudSDKException as e:
        if '450094-请求处理中，请稍候' in e.message:
            sleep(randint(0, 20))
            uc = create_app(app_nm=app_nm)
        elif '450096-昵称重复，请重新输入' == e.message:
            print(f'{app_nm}当前名称的app已经存在，请使用现有app')
            app_id = get_app_list(uc, app_nm)
            app_id = app_id[0]['AppBizId']
            uc.bot_biz_id = app_id
    return uc


def delete_app(use_config):
    biz_id = use_config.bot_biz_id
    request_action(use_config, 'DeleteApp', {'AppBizId': biz_id, 'AppType': 'knowledge_qa'})
    return


def config_app(use_config):
    params = {
        'AppBizId': use_config.bot_biz_id,
        'AppType': 'knowledge_qa',
        'BaseConfig': {
            'Name': use_config.bot_name,
            'Avatar': 'https://cdn.xiaowei.qq.com/static/lke/app-icon-knowledge_qa.png'
        },
        'AppConfig': {
            'KnowledgeQa': {
                'Model': {
                    'Name': 'DeepSeek-V3',
                    'HistoryLimit': 0,
                    'IsUseContext': False,
                    'Temperature': '0.1',
                    'TopP': '0.1'
                },
                'ThoughtModel': {
                    'Name': '思考模型高级版',
                    'HistoryLimit': 0,
                    'IsUseContext': False,
                    'Temperature': '0',
                    'TopP': '0.1'
                },
                'Output': {
                    'Method': 1,
                    'UseGeneralKnowledge': True
                },
                'Search': [{
                    'Type': 'doc',
                    'IsEnabled': True,
                    'DocTopN': 6,
                    'Confidence': 0.7
                }],
                'SearchStrategy': {
                    'StrategyType': 0,
                    'TableEnhancement': True
                }
            }
        }
    }
    try:
        res = request_action(use_config, 'ModifyApp', params)
    except TencentCloudSDKException as e:
        if e.message == '450024-系统错误':
            print(f'{use_config.bot_name}app参数配置出错，请修正参数')
    return


def get_publish_status(uc):
    params = {
        'BotBizId': uc.bot_biz_id
    }
    res = request_action(uc, 'DescribeRelease', params)
    return res['Response']


def publish_app(uc):
    params = {
        'BotBizId': uc.bot_biz_id
    }
    request_action(uc, 'CreateRelease', params)
    pub_sta = get_publish_status(uc)
    while pub_sta['StatusDesc'] != '发布成功':
        sleep(5)
        pub_sta = get_publish_status(uc)
    return


def get_app_key(uc):
    params = {
        'AppBizId': uc.bot_biz_id,
    }
    res = request_action(uc, 'GetAppSecret', params)
    return res['Response']['AppKey']


if __name__ == '__main__':
    uc1 = create_app()
    config_app(uc1)
    publish_app(uc1)
    # uc = useConfig
    # uc.bot_biz_id = '1901483768103305216'
    # delete_app(uc)
